#pragma once
#include "Socket.hpp"
#include <memory>
#include <functional>
#include <sys/types.h>
#include <sys/wait.h>

using Task_server = std::function<void(string&)>;

class Tcp_server
{
public:
    Tcp_server(int port = gdefault_port) : _socket(make_unique<Socket_tcp>(port)), _isrunning(false)
    {
        _socket->Create();
    }
    void Server_start()
    {
        _isrunning = true;
        string get_data;
        while (_isrunning)
        {
            _socket->Accept();        // 获取到客户端连接，并设置当前文件描述符
            _socket->Recev(get_data); // 接收客户端发送的数据
            LOG(LogLevel::INFO) << "get data from client: " << get_data;// 打印接收到的数据
            pid_t pid = fork();
            if(pid == 0)
            {
                _socket->Close(_socket->Socket_fd());
                _task_server(get_data);
                exit(0);
            }
            get_data.resize(0);// 清空缓冲区
            _socket->Close(_socket->Cur_rclientfd()); // 关闭当前文件描述符
            waitpid(pid, NULL, 0); // 等待子进程结束
        }
    }

    void Set_task_server(Task_server task_server)
    {
        _task_server = task_server;
    }
    unique_ptr<Socket>& Get_socket()
    {
        return _socket;
    }
private:
    Task_server _task_server;
    unique_ptr<Socket> _socket;
    bool _isrunning;
};
